import type { TreeDataItem } from 'ant-design-vue/es/tree';

import type { SysMenuResp } from '#/type/sys_menu';

/**
 * 将数组转换为树形结构
 */
const antTreeHandler = (
  arr: any[],
  key: number | string,
  title: number | string,
  pid: number | string,
) => {
  const nodes: Record<number, any> = {}; // ID -> 节点映射
  const roots: TreeDataItem[] = []; // 根节点集合
  // 初始化所有节点
  arr.forEach((item) => {
    nodes[item[key]] = {
      title: item[title],
      label: item[title],
      key: item[key],
      value: item[key],
      disabled: item.disabled ?? false,
      children: [],
    };
  });
  arr.forEach((item) => {
    const node = nodes[item[key]];
    const parent = nodes[item[pid]];
    parent ? parent.children.push(node) : roots.push(node);
  });
  return roots;
};

/**
 *  根据搜索文本过滤树形数据
 */
function antTreeFilter(
  tree: TreeDataItem[],
  searchText: string,
): TreeDataItem[] {
  // 空搜索返回完整树
  if (!searchText.trim()) return tree;
  const lowercaseSearch = searchText.toLowerCase();
  // 递归处理每个节点
  const processNode = (node: TreeDataItem): null | TreeDataItem => {
    // 深拷贝节点避免修改原数据
    const newNode: TreeDataItem = { ...node };
    let hasValidChild = false;

    // 处理子节点（后序遍历）
    if (newNode.children?.length) {
      const processedChildren = newNode.children
        .map((child) => processNode(child))
        .filter(Boolean) as TreeDataItem[];

      hasValidChild = processedChildren.length > 0;
      newNode.children = processedChildren;
    }
    // 判断当前节点是否匹配
    const isSelfMatch = newNode.title.toLowerCase().includes(lowercaseSearch);

    // 保留条件：自身匹配或包含有效子节点
    return isSelfMatch || hasValidChild ? newNode : null;
  };
  return tree
    .map((node) => processNode(node))
    .filter(Boolean) as TreeDataItem[];
}

/**
 * 根据指定父 key，获取其所有子孙节点的 key（深度优先遍历）
 */
function antTreeChildrenKeys(
  treeData: TreeDataItem[],
  key: number | string,
  pid: number | string,
): (number | string)[] {
  const result: (number | string)[] = [];
  const stack = [...treeData]; // 使用栈进行深度优先遍历

  let targetFound = false;

  while (stack.length > 0) {
    const node = stack.pop();
    if (!node) continue;

    if (targetFound && node[key] !== pid) {
      // 如果已经找到父节点区域，则收集所有后续子孙
      result.push(node[key]);
    }

    if (node[key] === pid) {
      // 找到父节点，开始收集它的 children
      targetFound = true;
      // 将其所有子节点压入栈
      if (node.children?.length) {
        stack.push(...[...node.children].reverse()); // reverse 保证顺序一致
      }
      continue;
    }

    // 如果还没找到父节点，继续找
    if (!targetFound && node.children?.length) {
      stack.push(...[...node.children].reverse());
    }
  }

  return result;
}

/**
 * 树形表格,将数组转换为树形结构
 */
const antTreeTableHandler = (
  arr: any[],
  key: number | string,
  pid: number | string,
) => {
  const nodes: Record<number, any> = {}; // ID -> 节点映射
  const roots: SysMenuResp[] = []; // 根节点集合
  // 初始化所有节点
  arr.forEach((item) => {
    nodes[item[key]] = { ...item, key: item[key] };
  });
  arr.forEach((item) => {
    const node = nodes[item[key]];
    const parent = nodes[item[pid]];
    if (parent) {
      parent.children = parent.children || [];
      parent.children.push(node);
    } else {
      roots.push(node);
    }
  });
  return roots;
};

export {
  antTreeChildrenKeys,
  antTreeFilter,
  antTreeHandler,
  antTreeTableHandler,
};
